<template>
  <van-pull-refresh
    :disabled="!enablePullRefresh"
    v-model="refreshing"
    @refresh="onRefresh"
  >
    <van-list
      class="refresh-list"
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      :finished-text="finishedText"
      :immediate-check="autoLoad"
      @load="onLoad"
    >
      <template #loading>
        <van-loading :color="rootThemeColor" type="spinner">{{ loadingText }}</van-loading>
      </template>
      <slot></slot>
    </van-list>
  </van-pull-refresh>
</template>

<script>
import {
  PullRefresh as VanPullRefresh,
  List as VanList,
  Loading as VanLoading
} from 'vant'
export default {
  name: 'RefreshList',
  inject: ['rootThemeColor'],
  components: {
    VanPullRefresh,
    VanList,
    VanLoading
  },
  props: {
    // 是否允许下拉刷新
    enablePullRefresh: {
      type: Boolean,
      default: true
    },
    // 是否允许上拉加载
    enablePullLoad: {
      type: Boolean,
      default: true
    },
    finishedText: {
      type: String,
      default: '没有更多了'
    },
    // 是否自动加载
    autoLoad: {
      type: Boolean,
      default: false
    },
    loadingText: {
        type: String,
        default: '加载中...'
    }
  },
  data () {
    return {
      loading: true,
      finished: false,
      error: false,
      refreshing: false
    }
  },
  beforeDestroy() {
    this.reset()
  },
  methods: {
    stopRefresh () {
      this.refreshing = false
    },
    stopLoad () {
      this.loading = false
    },
    completeLoad () {
      this.finished = true
    },
    showError () {
        this.error = true
    },
    reset () {
      this.finished = false
      this.loading = true
      this.error = false
    },
    isFinished() {
      return this.finished
    },
    onLoad () {
      if (this.enablePullLoad) {
        this.$emit('pull-load')
      }
    },
    onRefresh () {
      if (this.enablePullRefresh) {
        this.reset()
        this.$emit('pull-refresh')
      }
    }
  }
}
</script>
